package com.across.connect.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.across.connect.home.PlanHome;
import com.across.connect.model.Plan;

public class AjaxPlanAction extends AbstractAction {

	public ActionForward handleLogic(ActionMapping mapping,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		String action = request.getParameter("action");
		if ("load".equals(action)) {
			getMyPlan(response);
		}
		else if ("save".equals(action)) {
			saveMyPlan(request, response);
		}	
		return null;
	}
	
	private void getMyPlan(HttpServletResponse response){
		try {
			// 获取计划列表
			List<Plan> myplans = PlanHome.getInstance().getPlansByUserID(getHost().getId());
			StringBuffer sBuffer = new StringBuffer();
			if (myplans != null && myplans.size() > 0) {
				for (Plan plan : myplans) {
					sBuffer.append("<p><span class=\"time\">");
					sBuffer.append(plan.getDate());
					sBuffer.append("</span><a href=\"#\">");
					sBuffer.append(plan.getContent());
					sBuffer.append("</a></p>");
				}
			}
			else {
				sBuffer.append("<p><span class=\"time\"></span><a href=\"#\">尚无计划</a></p>");
			}
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html");
			PrintWriter pw = response.getWriter();
			pw.println(sBuffer.toString());
			pw.flush();
			pw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void saveMyPlan(HttpServletRequest request, HttpServletResponse response){
		try {
//			String content = new String((request.getParameter("content"))
//					.getBytes("ISO-8859-1"), "utf8");
			String content = URLDecoder.decode(request.getParameter("content"), "UTF8");
			StringBuffer sBuffer = new StringBuffer();
			if (StringUtils.isBlank(content)) {
				sBuffer.append("计划内容不能为空");
			}
			if (content.length() > 200) {
				sBuffer.append("计划内容不能超过200个字符");
			}
			String date = request.getParameter("date");
			if (StringUtils.isBlank(date)) {
				date = getNowDate();
			}
			PlanHome.getInstance().savePlanByUserID(
					String.valueOf(getHost().getId()), content, date);

			getMyPlan(response);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private String getNowDate() {
		Date d = new Date();
		SimpleDateFormat s = new java.text.SimpleDateFormat("yyyy-MM-dd");
		return s.format(d);
	}
}
